package org.aurora.module.user.facade;

import org.apache.dubbo.config.annotation.DubboService;
import org.aurora.framework.boot.rpc.dubbo.annotation.Facade;
import org.aurora.module.user.api.facade.UserFacadeService;
import org.aurora.module.user.api.facade.request.UserRequest;
import org.aurora.module.user.api.facade.response.UserAuthResponse;
import org.aurora.module.user.api.facade.validator.UserGroups;
import org.aurora.module.user.domain.entity.User;
import org.aurora.module.user.domain.service.UserService;
import org.aurora.module.user.facade.converter.UserFacadeConverter;
import org.springframework.validation.annotation.Validated;

import java.util.Objects;

/**
 * UserFacadeServiceImpl
 * <pre>
 * description:
 * create date: 2025-03-23 18:19:50
 * </pre>
 *
 * @author cao.yong
 */
@DubboService(version = "1.0.0")
public class UserFacadeServiceImpl implements UserFacadeService {

    private final UserService userService;

    public UserFacadeServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Facade
    @Override
    public UserAuthResponse authByUsername(@Validated({UserGroups.UsernameAndPassword.class}) UserRequest userRequest) {
        User user = userService.findByUsername(userRequest.getUsername());
        if (Objects.nonNull(user) && user.getPassword().equals(userRequest.getPassword())) {
            return UserAuthResponse.success(UserFacadeConverter.INSTANCE.mapToUserInfo(user));
        }
        return UserAuthResponse.failure(404, "用户不存在");
    }

    @Facade
    @Override
    public UserAuthResponse authByTelephone(@Validated({UserGroups.TelephoneAndPassword.class}) UserRequest userRequest) {
        User user = userService.findByTelephone(userRequest.getTelephone());
        if (Objects.nonNull(user) && user.getPassword().equals(userRequest.getPassword())) {
            return UserAuthResponse.success(UserFacadeConverter.INSTANCE.mapToUserInfo(user));
        }
        return UserAuthResponse.failure(404, "用户不存在");
    }
}
